package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.LogService;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class SignonServlet extends HttpServlet {
    private static final String View_Main = "/WEB-INF/jsp/catalog/Main.jsp";
    private static final String SIGNON_FORM = "/WEB-INF/jsp/account/SignonForm.jsp";


    private String username;
    private String password;
    private String msg = "Invalid username or password. Signon failed.";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        //获得输入的验证码值
        String value1 = req.getParameter("vCode");
        /*获取图片的值*/
        String value2 = (String) session.getAttribute("checkcode");
        Boolean isSame = false;
        /*对比两个值（字母不区分大小写）*/
        if (value2.equalsIgnoreCase(value1)) {
            isSame = true;
        }

        if (isSame) {
            username =req.getParameter("username");
            password =req.getParameter("password");

            AccountService accountService = new AccountService();
            Account account = accountService.getAccount(username, password);

            if(account ==null)

            {
                session.setAttribute("msg", msg);
                req.getRequestDispatcher(SIGNON_FORM).forward(req, resp);
            }else

            {
                session.setAttribute("account", account);
                req.getRequestDispatcher(View_Main).forward(req, resp);
            }


        } else {

            //验证码输入错误后刷新界面，重新生成验证码


            Account account = (Account)session.getAttribute("account");
            if(account != null){
                HttpServletRequest httpRequest= req;
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();

                String logInfo = logService.logInfo(" ") + strBackUrl + username+" 登录";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }

            req.getRequestDispatcher(SIGNON_FORM).forward(req, resp);
        }

    }





}




